<template>
    <div class="power-list">
        <el-dialog
            width="65%"
            title="查看权限"
            :visible.sync="approvalTableVisible"
        >
            <div class="top-mag">
                <div class="line-msg">
                    AD账户：{{itemData.ad}}
                    <span class="name-span">姓名：{{itemData.userNm}}</span>
                </div>
                <div class="line-msg">
                    <span>部门：{{itemData.deptNm}}</span>
                    <span class="btn">
                        <span class="red" @click="delectItem()">删除</span>
                        <span @click="addVisible = true">新增</span>
                    </span>
                </div>
            </div>
            <el-table size="mini" :border="true" 
                :data="gridData" 
                @selection-change="tableSelectChange"
            >
                <el-table-column align="center" type="selection" width="55"></el-table-column>
                <el-table-column align="center" property="viewTopDept" width="130" label="一级部门"></el-table-column>
                <el-table-column align="center" property="viewSubDept" label="子部门"></el-table-column>
                <el-table-column align="center" label="查看最高级别">
                    <template slot-scope="scope">
                        <span>{{showleveName(scope.row.viewPosLevel)}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" property="viewAd" label="AD账号"></el-table-column>
                <el-table-column align="center" property="viewName" label="姓名"></el-table-column>
                <el-table-column align="center" width="130" label="工作计划/回顾">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="gridData[scope.$index].viewWorkplan"
                            active-color="#13ce66"
                            inactive-color="#c2bdbd"
                            active-value="1"
                            inactive-value="0">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="130" label="访客">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="gridData[scope.$index].viewVisit"
                            active-color="#13ce66"
                            inactive-color="#c2bdbd"
                            active-value="1"
                            inactive-value="0">
                        </el-switch>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" type="primary" @click="submitData()">保 存</el-button>
            </span>
            <el-dialog
                width="30%"
                title="新增权限"
                class="add-parduser"
                :visible.sync="addVisible"
                :before-close="closedialog"
                append-to-body
            >
                <div class="item-complete" style="display:flex;" v-if="!topviewName">
                    <span>请选择人员：</span>
                    <el-select
                        size="mini"
                        v-model="adduser"
                        clearable
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入关键词"
                        :remote-method="querySearchAsync"
                        :loading="loading">
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div v-if="!adduser">
                    <div class="item-complete">
                        <span>一级部门：</span>
                        <el-select 
                            clearable
                            size="mini"
                            filterable
                            v-model="topviewName"
                            @change="viewNames = []"
                            placeholder="请选择">
                            <el-option
                                v-for="item in deptoptions"
                                :key="item.value"
                                :label="item.key"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="item-complete">
                        <span>子部门：</span>
                        <span v-for="(tag,index) in viewNames" :key="index">
                            <el-tag
                                size="small"
                                closable
                                :disable-transitions="false"
                                @close="handleClose(tag)">
                                {{tag}}
                            </el-tag> <span class="right-sing" v-if="viewNames.length !== index+1">/</span>
                        </span>
                        <el-select 
                            size="mini"
                            class="chose-select"
                            v-if="showAuto" 
                            v-model="otherName" 
                            placeholder="请选择"
                            @change="handleSelect"
                        >
                            <el-option
                            v-for="item in otheroptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                        <el-button 
                            v-else 
                            size="mini"
                            :class="viewNames.length != 0 ? 'button-new-tag':''"
                            @click="showAutoInput"
                        >+ 新增子部门</el-button>
                    </div>
                    <div class="item-complete">
                        <span>查看最高级别：</span>
                        <el-select size="mini" clearable v-model="submitObj.viewPosLevel" placeholder="请选择岗位层级">
                            <el-option
                                v-for="(item,index) in levelList"
                                :key="index"
                                :label="item.name"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </div>
                </div>
                <div class="item-complete">
                    <span>工作计划/回顾 权限：</span>
                    <el-switch
                        v-model="submitObj.viewWorkplan"
                        active-color="#13ce66"
                        inactive-color="#c2bdbd"
                        active-value="1"
                        inactive-value="0">
                    </el-switch>
                </div>
                <div class="item-complete">
                    <span>访客 权限：</span>
                    <el-switch
                        v-model="submitObj.viewVisit"
                        active-color="#13ce66"
                        inactive-color="#c2bdbd"
                        active-value="1"
                        inactive-value="0">
                    </el-switch>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="clearthisBox()">清 空</el-button>
                    <el-button size="mini" type="primary" @click="commitcomplete()">确 定</el-button>
                </div>
            </el-dialog>
        </el-dialog>
    </div>
</template>
<script>
import Vue from "vue";
import {
    authDeptgetApi,
    getByAdOrNmData,
    authViewgSaveApi,
    deptgetByLoginAd,
    getAuthViewListApi
} from "@/api/getData";
import { alertMessage } from '@/config/myUtil';
import { Table, TableColumn,Tag} from "element-ui";
Vue.use(Tag);
Vue.use(Table);
Vue.use(TableColumn);
export default {
    name:"PowerList",
    props:{
        deptoptions:{
            type:Array,
            default:[],
        }
    },
    data(){
        return {
            addVisible:false,
            approvalTableVisible: false,
            itemData: {},
            gridData:[],
            delectList:[],
            adduser:"",
            options:[],
            otheroptions:[],
            loading:false,
            // 二级以下部门
            topviewName:'',
            viewNames:[],
            otherName:'',
            showAuto:false,
            levelList: [
                { name: "六级-普通员工", value: 6 },
                { name: "五级-基层管理者", value: 5 },
                { name: "四级-部门副职", value: 4 },
                { name: "三级-部门负责人", value: 3 },
                { name: "二级-公司领导", value: 2 },
                { name: "一级-总经理", value: 1 }
            ],
            submitObj:{
                ad: "",
                viewAd:"",
                viewName:"",
                viewPosLevel: "",
                viewSubDept: "",
                viewTopDept: "",
                viewVisit: "1",
                viewWorkplan: "1",
            },
            showleveName:(num)=>{
                var name = ''
                this.levelList.map((item)=>{
                    if(item.value == num){
                        name = item.name;
                    }
                });
                return name;
            }
        }
    },
    methods:{
        changeStatus(item){
            if(item.ad){
                this.itemData = item;
                this.approvalTableVisible = true;
                this.initDataList(item.ad)
            }
        },
        async initDataList(ad){
            try {
                let data = await getAuthViewListApi({ad:ad});
                this.gridData = data;
            } catch (error) {
                console.log(error)
            }
        },
        async querySearchAsync(queryString) {
            try {
                if(queryString !== ''){
                    this.loading = true
                    let data = await getByAdOrNmData({ key: queryString });
                    data.map((item)=>{
                        item.label = `${item.userNm}—${item.deptNm}`;
                        item.value = `${item.ad}&${item.userNm}`;
                    });
                    this.loading = false;
                    this.options = data;
                }else{
                    this.options = []
                }
            } catch (error) {
                console.log(error)
            }
        },
        // 二级以下部门
        async querybumen(parDept,rank){
            try {
                if(this.topviewName){
                    let data = await authDeptgetApi({
                        topDept:this.topviewName,
                        time:rank||0,
                        parDept:parDept
                    });
                    var list = data.map((item)=>{
                        return {
                            key:item,
                            value:item
                        }
                    });
                    this.otheroptions = list;
                    if(this.otheroptions.length==0){
                        this.showAuto = false;
                        alertMessage("此部门无下级部门",'warning')
                    }
                }
            } catch (error) {
                console.log(error)
            }
        },
        async submitData(){
            try {
                if(this.gridData.length > 0 ){
                    this.gridData.map((item)=>{
                        delete item.authId;
                    })
                };
                let data = await authViewgSaveApi(this.gridData.length == 0 ? [{ad:this.itemData.ad}] : this.gridData);
                if(data == 1){
                   alertMessage('保存成功') 
                }else{
                   alertMessage('保存失败','error')
                }
                this.approvalTableVisible = false;
            } catch (error) {
                console.log(error)
            }
        },
        tableSelectChange(selList){
            this.delectList = selList;
        },
        delectItem(){
            if(this.delectList.length > 0){
                var oldarr = JSON.parse(JSON.stringify(this.gridData));
                this.gridData.map((item, index) => {
                    for (let i = 0; i < this.delectList.length; i++) {
                            if(item.authId){
                                if(item.authId == this.delectList[i].authId){
                                    delete oldarr[index]
                                }
                            }else{
                                if(item.viewAd == this.delectList[i].viewAd){
                                    delete oldarr[index]
                                }
                            }
                        }
                });
                let newarr = [];
                oldarr.map((item)=>{
                    if(item){
                        newarr.push(item)
                    }
                })
                this.gridData = newarr;
            }else{
               alertMessage('请选择要删除的部门!','warning');
            }
        },
        showAutoInput(){
            if(this.topviewName){
                this.showAuto = true;
                var name = this.viewNames[this.viewNames.length - 1] || this.topviewName
                this.querybumen(name,this.viewNames.length);
            }else{
                alertMessage("请先选择一级部门",'warning')
            }           
        },
        handleSelect(){
            this.viewNames.push(this.otherName);
            this.showAuto = false;
            this.otherName = '';
            this.otheroptions = [];
        },
        handleClose(tag){
            this.viewNames.splice(this.viewNames.indexOf(tag), 1);
        },
        closedialog(){
            this.clearthisBox();
            this.addVisible = false;
        },
        clearthisBox(){
            this.adduser = "";
            this.topviewName = "";
            this.viewNames = [];
            this.submitObj.viewPosLevel = "";
            this.showAuto = false;
        },
        commitcomplete(){
            this.submitObj.ad = this.itemData.ad;
            this.submitObj.viewTopDept = this.topviewName;
            this.submitObj.viewAd = "";
            this.submitObj.viewName = "";
            this.submitObj.viewSubDept = "";
            if(this.adduser){
                this.submitObj.viewAd = this.adduser.split('&')[0];
                this.submitObj.viewName = this.adduser.split('&')[1];
            };
            if(this.viewNames.length > 0){
                this.viewNames.map((item,index)=>{
                    this.submitObj.viewSubDept += item + (this.viewNames.length == index+1 ? '' : '/');
                })
            };
            if(this.submitObj.viewAd || this.submitObj.viewTopDept){
                var newObj = JSON.parse(JSON.stringify(this.submitObj));
                this.gridData.push(newObj);
                this.otherName = "";
                this.adduser = "";
                this.viewNames = [];
                this.topviewName = "";
                this.addVisible = false;
            }else{
                alertMessage("请选择人员或者部门","warning")
            }
        },
    },
}
</script>
<style lang="less" scoped>
@import url("../less/approvalTable.less");
</style>